<?php
namespace Frieza\Modules\Decoration\Controllers;

use function Clue\StreamFilter\fun;
use Doraemon\service\Decoration\FormatSubject;
use Doraemon\tools\LinkFormat;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Decoration\Adv as mAdv;
use Doraemon\model\Decoration\Category as mCategory;
use Doraemon\service\Decoration\Cache as sCache;
use Doraemon\model\Decoration\Subject as mSubject;
use Doraemon\service\Decoration\Main as sMain;
use Kafka\Exception;
use Doraemon\tools\LinkConf;
use League\Flysystem\Adapter\CanOverwriteFiles;
use Doraemon\tools\BlockTypeMapping;
use Doraemon\pockets\constInterface\LinkConf as ConfLink;
use Doraemon\model\Decoration\SubjectGroup;



class MainAdvController extends Controller
{
    const PAGE_SIZE = 500;


    const STATUS_ARRAY_SELECT = [
        mAdv::STATUS_NOPEN => '未开启',
        mAdv::STATUS_OPEN => '开启',
        mAdv::STATUS_CLOSE=>'关闭',
    ];



    const LINK_TYPE = [
        ConfLink::LINK_BLANK=>"经验文章",
        ConfLink::LINK_ARTICLE=>"整屋案例",
        ConfLink::LINK_GUIDE=>"指南",
        ConfLink::LINK_SPECIAL_ITEM=>"专题",
        ConfLink::LINK_TOPIC_DETAIL=>"话题",
        ConfLink::LINK_INSPIRATION_SET=>"灵感集"
    ];

    const TYPE_TO_OBJ_TYPE= [
        ConfLink::LINK_BLANK=>"blank_id",
        ConfLink::LINK_ARTICLE=>"article_id",
        ConfLink::LINK_GUIDE=>"guide_id",
        ConfLink::LINK_SPECIAL_ITEM=>"special_id",
        ConfLink::LINK_TOPIC_DETAIL=>"topic_id",
        ConfLink::LINK_INSPIRATION_SET=>"ideabook"

    ];


    const ADV_STATUS =[
        mAdv::STATUS_NOPEN => "未开始",
        mAdv::STATUS_OPEN=>'开启',
        mAdv::STATUS_CLOSE=> '已失效'

    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
        Admin::script($this->resetEdittime());
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }

        $data = [];
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
                if($_k == 'date_time') {
                    if ($where[$_k]['start'] <> '') {
                        $where['start_time[>=]'] = $where[$_k]['start'];
                        unset($where[$_k]['start']);
                    }
                    if ($where[$_k]['end'] <> '') {
                        $where['end_time[<]'] = $where[$_k]['end'];
                        $where[$_k]['end'];
                    }
                    unset($where[$_k]);
                }
            }
        }

        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }



    public function listAction($request = []){

        $tab = new Tab();

        $tab->add('全部资源位', self::getShowtype($request, 0));
        foreach(mAdv::SHOW_TYPE as $_sk=>$_sv) {
            $tab->add($_sv, self::getShowtype($request, $_sk));
        }

        return $tab->render();
    }

    public function getShowtype($request, $showType = 0){
        if(isset($request['AND']['rela_id']) && !isset($request['AND']['id'])){
            $sql = 'select * from `hhz_decoration_adv` where FIND_IN_SET('.$request['AND']['rela_id'].',rela_id)';
            $relaId = mAdv::query($sql)->fetchAll();
            $request['AND']['id'] = array_column($relaId, 'id');
            unset($request['AND']['rela_id']);
        }
        if($showType>0) {
            $request['AND']['show_type'] = $showType;
        }
        if(empty($request['AND'])){
            unset($request['AND']);
        }

        $data = sMain::getAdv($request);

        $gridModel = new pGridDataModel($data['list'], $data['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($showType) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();

            if($showType>0){
                $grid->disableFilter();
            }else {
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('date_time', '资源时间')->datetime()->condition($_GET);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('show_type', '资源位置')->select(mAdv::SHOW_TYPE);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('name', '名称')->placeholder('请输入名称');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('group_title', '内容卡片标题')->placeholder();
                    });
                });
                $grid->fixColumns(0, -1);
            }

            $grid->column('id')->sort();;
            $grid->column('rela_name', '关联分类');
            $grid->column('sid_name', '关联主题');
            $grid->column('show_type', '资源位置')->display(function(){
                return mAdv::SHOW_TYPE[$this->show_type];
            });
            $grid->column('name', '名称')->display(function(){
                if(!empty($this->name)) {
                    return '<p style="color:' . $this->font_color . ';">' . $this->name . '</p>';
                }else{
                    return '<p style="color:' . $this->font_color . ';">暂空</p>';
                }

            });
            $grid->column('group_title', '内容卡片');
            $grid->column('is_point', '背景是否透明')->display(function(){
                if($this->is_point) {
                    return '是';
                }else{
                    return '否';
                }
            });
            $grid->column('pic_id_url', '封面')->display(function(){
                if(!empty($this->pic_id_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >';
                }
            });
            $grid->column('sort', '权重');

            if (in_array($showType, [4012, 4013])) {
                $grid->column('pos', '位置');
                $grid->column('obj_id', '内容/wiki id');
            }

            if($showType > 0) {
                $grid->column('link', '链接')->limit(30);
            }else {
                $grid->column('link', '链接信息')->linkSelect();
            }

            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '更新时间');
            $grid->column('status', '状态')->display(function(){
                switch ($this->status){
                    case 0:$st = '未生效';break;
                    case 1:$st = '开启';break;
                    case 2:$st = '已失效';break;break;
                }
                return $st;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();

                if($actions->row->status >= 2) {
                    $actions->disableEdit();
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }



    public function sortmoudle(Request $request){
        $params = $request->all();

        if($params['sort'] && is_array($params['sort'])){
            $result = mAdv::action(function()use($params){
                $params['sort'] = array_values(array_reverse(array_flip($params['sort'])));
                foreach($params['sort'] as $_sort=>$_v){
                    $this->updateContentGroup($_v , ['sort' => $_sort]);
                    if(!SubjectGroup::updateData(['sort' => $_sort], ['id' => $_v])){
                        return false;
                    }
                }
                return true;
            });
        }
        if($result){
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }








    public static function save(Request $request,$parentId = 0, $sonId = 0, $sid = 0, $id = 0 ,$show_type = 0)
    {
        if(strpos($request->url(), '/decoration/subject/')){
            $sid = $parentId;
            $id = $sonId;
            $parentId = $sonId = 0;
        }
        $preUrl = '/admin/decoration';
//        if($sid > 0){
//            $preUrl.= '/mainadv/subjectlist/'.$sid;
//        }
        switch($show_type){
            case mAdv::SHOW_TYPE_5:
                $preUrl .='/mainadv/subjectlist/'.$sid;
                break;
            case mAdv::SHOW_TYPE_6:
                $preUrl .='/mainadv/taglist/'.$sid;
                break;
            case mAdv::SHOW_TYPE_1:
                $preUrl .="/maincategory/subjectlist/".$sonId;
                break;
            case mAdv::SHOW_TYPE_2:
                $preUrl .="";
                break;
        }

        $get = $_SERVER["QUERY_STRING"];
        $params = $request->all();
        if(isset($params['id']) && $params['id'] > 0 && !isset($params['name'])){
            $param = [
                'link_type'=> $params['link_type'],
                'link_params'=> json_encode($params['link_params'], true),
                //'link_url'=> $params['link_url'],
                'link'=> $params['link_url'],
                'admin_id' => Admin::user()->id,
            ];
            $result = mAdv::updateData($param,['id'=>$params['id']]);
        }else {

            if (in_array($params['show_type'], [mAdv::SHOW_TYPE_2, mAdv::SHOW_TYPE_4])) {
                $where = [
                    'show_type' => $params['show_type'],
                    'sort' => $params['sort'],
                    'sort[>]' => 0,
                    'status[<]' => mAdv::STATUS_CLOSE,
                ];
                if (isset($request['id'])) {
                    $where['id[!]'] = $params['id'];
                }
                if (mAdv::getOneByWhere($where, 'id')) {
                    $error = new MessageBag([
                        'title' => '权重不能重复'
                    ]);

                    return back()->with(compact('error'));
                }
            }
            if (in_array($params['show_type'], [4012, 4013])) {
                if (empty($params['pos']) || empty($params['obj_id'])) {
                    $error = new MessageBag([
                        'title' => '位置必须大于0或者内容id必填'
                    ]);

                    return back()->with(compact('error'));
                }
            }
            if (!in_array($params['show_type'], [4012, 4013]) && (!isset($params['id']) && empty($params['link_params']))) {
                $error = new MessageBag([
                    'title' => '链接不能为空'
                ]);

                return back()->with(compact('error'));
            }

            if ($params['category_1']) {
                $params['category_1'] = array_filter($params['category_1']);
                if (!empty($params['category_1'])) {
                    $params['rela_id'] = implode(',', $params['category_1']);
                }
                unset($params['category_1']);
            }
            if ($params['category_2']) {
                $params['category_2'] = array_filter($params['category_2']);
                if (!empty($params['category_2'])) {
                    $params['rela_id'] = implode(',', $params['category_2']);
                }
                unset($params['category_2']);
            }

            if (empty($params['rela_id']) && empty($params['sid'])) {
                $error = new MessageBag([
                    'title' => '分类或者主题不能为空'
                ]);

                return back()->with(compact('error'));
            }
            if (empty($params['sid']) && empty($params['name'])) {
                $error = new MessageBag([
                    'title' => '名称不能为空'
                ]);

                return back()->with(compact('error'));
            }
            if (!empty($params['rela_id'])) {
                $category = mCategory::getAllByWhere(['id' => explode(',', $params['rela_id'])]);
                $category = array_column($category, 'is_cover');
                $category = array_filter($category);
                if (!empty($category) && empty($params['pic_id'])) {
                    $error = new MessageBag([
                        'title' => '关联的分类需要上传封面'
                    ]);

                    return back()->with(compact('error'));
                }
            }
            if (in_array($params['show_type'], [mAdv::SHOW_TYPE_2, mAdv::SHOW_TYPE_3, mAdv::SHOW_TYPE_4]) && empty($params['pic_id'])) {
                $error = new MessageBag([
                    'title' => '没有上传封面'
                ]);

                return back()->with(compact('error'));
            }

            if ($params['show_type'] == mAdv::SHOW_TYPE_5) {
                if ($params['select_group'] == 1) {
                    //创建,名称不能重复
                    if (!empty($params['group_title1']) && mAdv::getOneByWhere(['status[!]' => mCategory::STATUS_DELETE, 'group_title' => $params['group_title1'],'sid'=>$params['sid']], 'id')) {
                        $error = new MessageBag([
                            'title' => '内容卡片已经存在'
                        ]);

                        return back()->with(compact('error'));
                    }
                    $params['group_title'] = $params['group_title1'];
                } else {
                    //选中
                    $groupTitle = mAdv::getAllByWhere(['status[!]' => mCategory::STATUS_DELETE, 'GROUP' => 'group_title'], ['group_title', 'sort', 'id']);
                    $groupTitleSorts = array_column($groupTitle, 'sort', 'group_title');
                    if (!empty($params['group_title2'])) {
                        $params['group_title'] = $params['group_title2'];
                        $params['sort'] = !empty($params['sort']) ? $params['sort'] : $groupTitleSorts[$params['group_title2']];
                    } else {
                        $params['sort'] = !empty($params['sort']) ? $params['sort'] : '';
                    }
                }
                if (empty($params['sort'])) {
//                    $error = new MessageBag([
//                        'title' => '内容卡片权重不能为空'
//                    ]);
//
//                    return back()->with(compact('error'));
                } else {
                    if (isset($params['id']) && !empty($params['group_title2'])) {
                        $groupId = mAdv::getAllByWhere(['status[!]' => mCategory::STATUS_DELETE, 'group_title' => $params['group_title2']], 'id');
                        if (!empty($groupId)) {
                            try {
                                mAdv::updateData(['sort' => $params['sort']], ['id' => $groupId]);
                            } catch (Exception $e) {
                                $error = new MessageBag([
                                    'title' => $e
                                ]);

                                return back()->with(compact('error'));
                            }
                        }
                    }
                }
            }

            $param = [
                'show_type' => $params['show_type'],
                'rela_id' => isset($params['rela_id']) ? $params['rela_id'] : '',
                'sid' => isset($params['sid']) ? $params['sid'] : 0,
                'name' => isset($params['name']) ? $params['name'] : '',
                'font_color' => isset($params['font_color']) ? $params['font_color'] : '',
                'group_title' => isset($params['group_title']) ? $params['group_title'] : '',
                'is_point' => isset($params['is_point']) ? $params['is_point'] : 0,
                'sort' => isset($params['sort']) ? $params['sort'] : 0,
                'link' => !empty($params['link_url']) ? $params['link_url'] : (isset($params['id']) ? $params['link'] : ''),
                'link_type'=> $params['link_type'],
                'link_params'=> json_encode($params['link_params'], true),
                //'link_url'=> $params['link_url'],
                'pic_id' => isset($params['pic_id']) ? $params['pic_id'] : '',
                'start_time' => $params['start_time'],
                'end_time' => $params['end_time'],
                'pos' => $params['pos'] ?? 0,
                'obj_id' => $params['obj_id'] ?? '',
                'admin_id' => Admin::user()->id,
            ];

            if($param['start_time'] <= date('Y-m-d H:i:s') && $param['end_time'] > date('Y-m-d H:i:s')){
                $param['status'] = mAdv::STATUS_OPEN ;
            }else if($param['start_time'] > date('Y-m-d H:i:s')){
                $param['status'] = mAdv::STATUS_NOPEN ;
            }else if($param['end_time'] <= date('Y-m-d H:i:s')){
                $param['status'] = mAdv::STATUS_CLOSE ;
            }
            if (!isset($params['id'])) {
                $param['add_time'] = date('Y-m-d H:i:s');
                $result = mAdv::addData($param);
                $param['id'] = $result;
            } else {
                if($param['start_time'] <= date('Y-m-d H:i:s') && $param['end_time'] > date('Y-m-d H:i:s')){
                    $param['status'] = mAdv::STATUS_OPEN ;
                }else if($param['start_time'] > date('Y-m-d H:i:s')){
                    $param['status'] = mAdv::STATUS_NOPEN ;
                }else if($param['end_time'] <= date('Y-m-d H:i:s')){
                    $param['status'] = mAdv::STATUS_CLOSE ;
                }
                $result = mAdv::updateData($param, ['id' => $params['id']]);
                $param['id'] = $params['id'];
            }
        }
        if($result){
            $success = new MessageBag([
                'title' => '操作成功'
            ]);

            return redirect($preUrl)->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return redirect($preUrl)->with(compact('error'));
        }

    }


    public function saveLink(Request $request,  $sid = 0, $id = 0){
        $params = $request->all();
        $param = [
            'link' => !empty($params['link_url']) ? $params['link_url'] : (isset($params['id']) ? $params['link'] : ''),
            'link_type'=> $params['link_type'],
            'link_params'=> json_encode($params['link_params'], true),
            'admin_id' => Admin::user()->id,
        ];
        $result = mAdv::updateData($param, ['id' => $id]);

        if($result){
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function create(Request $request,Content $content, $parentId = 0, $sonId = 0, $sid = 0, $aid = 0 , $show_type=0){
        if(strpos($request->url(), '/decoration/subject/')){
            $sid = $parentId;
            $aid = $sonId;
            $parentId = $sonId = 0;
        }
         $requests = $request;
         $request = $request->all();
         if($sid > 0) {
                $request['sid'] = $sid;
                $subject_info = mSubject::getOneByWhere(['id'=>$sid]);
         }
         if($aid > 0){
             $title = "编辑";
            $request['id'] = $aid;
            $preUrl = '/mainadv/save/'.$parentId.'/'.$sonId.'/' . $sid . '/'.$aid.'/'.$show_type.'/adv';
        }else{
             $title = "新增";
             $preUrl ='/mainadv/save/'.$parentId.'/'.$sonId.'/' . $sid . '/0/'.$show_type.'/adv';
         }

         //设置导航面包屑
         switch($show_type){
             case mAdv::SHOW_TYPE_5:
             case mAdv::SHOW_TYPE_6:
                $content->breadcrumb(
                     ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
                     ['text' => $subject_info['name'].'-内容页', 'url' => '/decoration/mainadv/subjectlist/'.$sid],
                     ['text' => $title, 'url' => '/decoration/mainadv/content/create/'.$parentId.'/'.$sonId.'/'.$sid.'/'.$aid."/".$show_type]);
                 break;
             case mAdv::SHOW_TYPE_1:
                 $content->breadcrumb(
                     ['text' => '装修分类页', 'url' => '/decoration/maincategory'],
                     ['text' => '关联主题', 'url' => '/decoration/maincategory/subjectlist/'.$sonId],
                     ['text' => $title, 'url' => '/decoration/mainadv/content/create/'.$parentId.'/'.$sonId.'/'.$sid.'/'.$aid."/".$show_type]
                 );
                 break;

         }
        //设置导航面包屑

        $request = self::_filterWhere($request);
        $subject = mSubject::getAllByWhere(['status'=>mSubject::STATUS_OPEN],['id','name']);
        $subjects = [];
        if (!empty($subject)) {
            foreach ($subject as &$_v) {
                if($sid) {
                    if ($sid == $_v['id']) {
                        $subjects[$_v['id']] = $_v['name'];
                        break;
                    }
                }else{
                    $subjects[$_v['id']] = $_v['name'];
                }
            }
        }
        return $content->header($title)
            ->body(self::advs($request, $subjects, [$parentId, $sonId], $sid,  '/admin/decoration'.$preUrl,$show_type));
    }


    public function advs($request, $subjects, $cid = [], $sid, $postUrl , $show_type  = 0){
        if($show_type){
            $show_type = [$show_type => mAdv::SHOW_TYPE[$show_type]];
        }else{
            $show_type = mAdv::SHOW_TYPE;
            if(!$sid){
                $show_type = [
                    mAdv::SHOW_TYPE_2 => mAdv::SHOW_TYPE[mAdv::SHOW_TYPE_2]
                ];
            }
        }
        $category = mCategory::getAllByWhere(['status'=>mCategory::STATUS_OPEN],['id','title','parent_id']);
        $categorys = [];
        $cid = array_filter($cid);
        if (!empty($category)) {
            foreach ($category as &$_v) {
                if($_v['parent_id'] == 0){
                    $categorys['parent'][$_v['id']] = $_v['title'];
                    if(!empty($cid) && !in_array($_v['id'], $cid)){
                        unset($categorys['parent'][$_v['id']]);
                    }
                }else if(isset($categorys['parent'][$_v['parent_id']])){
                    $categorys['son'][$_v['id']] = $_v['title'];
                    if(!empty($cid) && (!in_array($_v['id'], $cid) && !in_array($_v['parent_id'], $cid))){
                        unset($categorys['son'][$_v['id']]);
                    }
                }
            }
        }
        if(!isset($categorys['parent']) || !isset($categorys['son']) || empty($subjects)) {
            //如果没有一级二级分类或者缺少主题，无法创建广告位
            unset($show_type);
        }
        //获取卡片名称
        $groupTitle = [];
        $groupTitleWhere = [
            'group_title[!]'=>'',
            'status[!]' => mCategory::STATUS_DELETE,
            'GROUP' => 'group_title'
        ];
        if($sid > 0) {
            $groupTitleWhere['sid'] = $sid;
        }
        $groupTitle = mAdv::getAllByWhere($groupTitleWhere, ['group_title', 'sort']);


        if(!empty($request['AND']['id'])){
            $data = mAdv::getOneByWhere(['id'=>$request['AND']['id']]);
            $data['link'] = [
                'link_type'=> $data['link_type'],
                'link_params'=> $data['link_params'],
                'link_url'=> $data['link_url'],
            ];
            $id = $request['AND']['id'];
        }else{
            $data = [];
            $id = 0;
        }
        $dataJsons = [
            'rela_id' => $data['rela_id'],
            'show_type' => $data['show_type'],
        ];
        $dataJson = json_encode($dataJsons, true);
        if(!empty($groupTitle)){
            $groupTitleHas = 1;
        }else{
            $groupTitleHas = 0;
        }

        $script =
            <<<SCRIPT
      var data_json = $.parseJSON('{$dataJson}');
      var groupTitle = {$groupTitleHas};
      var cur_id = {$id};
      var showtype = $('.show_type');
      var category_1 = $('input.category_1');
      var category_2 = $('input.category_2');
      var side = category_2.parents('.form-group').next('.form-group');
      var name = $('#name').parents('.form-group');
      var is_point = $('.is_point').parents('.form-group');
      var group_title1 = $('.group_title1').parents('.form-group');
      var group_title2 = $('.group_title2').parents('.form-group');
      var select_group = $('.select_group').parents('.form-group');
      var font_color = $('.font_color').parents('.form-group');
      
      category_1.parents('.form-group').hide();
      category_2.parents('.form-group').hide();
      side.hide();
      name.hide();
      is_point.hide();
      group_title1.hide();
      group_title2.hide();
      select_group.hide();
      font_color.hide();

      if(cur_id > 0){
          side.show();
          name.show();
          is_point.hide();
          select_group.hide();
          group_title1.hide();
          font_color.hide();
          var cid = data_json.rela_id.split(',');
          if(data_json.show_type == 4006){  
              $.each(category_2, function(ck, cv){ 
                    var cur = $(this); 
                    if($.inArray(cur.val(), cid) >= 0){
                        cur.iCheck('check');
                    }
              });
              category_1.parents('.form-group').hide();
              category_2.parents('.form-group').show();
              name.hide();
              font_color.show();
          }else if(data_json.show_type == 4007){
              $.each(category_1, function(ck, cv){ 
                    var cur = $(this); 
                    if($.inArray(cur.val(), cid) >= 0){
                        cur.iCheck('check');
                    }
              });
              category_1.parents('.form-group').show();
              category_2.parents('.form-group').hide();
              side.hide();
          }else if(data_json.show_type == 4008){
              category_1.parents('.form-group').hide();
              category_2.parents('.form-group').hide();
          }else if(data_json.show_type == 4009){
              category_1.parents('.form-group').hide();
              category_2.parents('.form-group').hide();
          }else if(data_json.show_type == 4010){
              select_group.show();
              //group_title1.hide();
              //group_title2.show();
              if(groupTitle > 0){
                  group_title1.hide();
                  group_title2.show();
              }else{
                  group_title1.show();
                  group_title2.hide();
              }
          }else if(data_json.show_type == 4011){
              is_point.show();
          }  
          
      }else{
//          $('input.link_type').first().iCheck('check');
//          $('input.link').val($('input.link_type').first().val());
      }
      
      
//       $('input.link_type').on('ifChecked ifUnchecked', function(event) {
//           if (event.type == 'ifChecked'){
//            $('input.link').val($(this).val());
//           }
//        });
   
        showtype.on('select2:select', function (e) { 

              side.show();
              name.show();
              is_point.hide();
              select_group.hide();
              group_title1.hide();
              group_title2.hide();
              font_color.hide();
              var data = e.params.data.id;
 if(data == 4006){
                  category_1.parents('.form-group').hide();
                  category_2.parents('.form-group').show();
                  name.hide();
                  font_color.show();
              }else if(data == 4007){
                  category_1.parents('.form-group').show();
                  category_2.parents('.form-group').hide();
                  side.hide();
              }else if(data == 4008){
                  category_1.parents('.form-group').hide();
                  category_2.parents('.form-group').hide();
              }else if(data == 4009){
                  category_1.parents('.form-group').hide();
                  category_2.parents('.form-group').hide();
              }else if(data == 4010){
                  select_group.show();
                  if(cur_id > 0 && groupTitle > 0){
                      group_title1.hide();
                      group_title2.show();
                  }else{
                      group_title1.show();
                      group_title2.hide();
                  }
              }else if(data == 4011){
                  is_point.show();
              }else if(data == 4012){
                        category_1.parents('.form-group').hide();
      category_2.parents('.form-group').hide();
      name.hide();
      is_point.hide();
      group_title1.hide();
      group_title2.hide();
      select_group.hide();
      font_color.hide();
              }else if(data == 4013){
                        category_1.parents('.form-group').hide();
      category_2.parents('.form-group').hide();
      name.hide();
      is_point.hide();
      group_title1.hide();
      group_title2.hide();
      select_group.hide();
      font_color.hide();
              }
        });
       
        
        $('.select_group').on('ifChecked ifUnchecked', function(event) {
           if (event.type == 'ifChecked' && event.currentTarget.defaultValue==1){
                group_title1.show();
                group_title2.hide();
                $('input.sort').parents('.form-group').show();
           }else{
                group_title1.hide();
                group_title2.show();
                $('input.sort').parents('.form-group').hide();
           }
           if(cur_id > 0){
               $('input.sort').parents('.form-group').show();
            }
        });
       
      

SCRIPT;


        Admin::script($script);
        //Admin::script('imgUpload.one();');
        $form = new Form($data);
        if(isset($request['AND']['id'])){
            $form->hidden('id');
        }

        $form->select('show_type', '位置')
            ->options($show_type)
            ->setWidth(4, 2)
            ->required('不能为空');
        ;

        $form->checkbox('category_1','关联一级分类')->options(isset($categorys['parent'])?$categorys['parent']:[]);
        if(isset($categorys['son'])) {
            $form->checkbox('category_2', '关联二级分类')->options(isset($categorys['son']) ? $categorys['son'] : []);
        }
        $form->select('sid', '关联主题')->options($subjects)->setWidth(4, 2);

        $groupTitles = array_column($groupTitle, 'group_title', 'group_title');
        if(!empty($groupTitles)) {
            if(isset($request['AND']['id'])) {
                $form->radio('select_group', '是否创建内容卡片')->options([1 => '是', 0 => '否'])->default(0)->setWidth(4, 2);
            }else{
                $form->radio('select_group', '是否创建内容卡片')->options([1 => '是', 0 => '否'])->default(1)->setWidth(4, 2);
            }
        }else{
            $form->radio('select_group', '是否创建内容卡片')->options([1 => '是'])->default(1)->setWidth(4, 2);
        }
        $form->select('group_title2', '选择内容卡片')->options($groupTitles)->default(function ()use($data){
            return isset($data['group_title'])?$data['group_title']:'';
        })->setWidth(4, 2);
        $form->text('group_title1', '创建内容卡片')->setWidth(4, 2);
        //$form->text('sort', '权重')->setWidth(4, 2);


        $form->text('name', '名称')->setWidth(4, 2);
        $form->color('font_color', '字体景色')->setWidth(4, 2);
        $form->radio('is_point', '背景透明')->options([0=>'否',1=>'是'])->setWidth(4, 2);
        $form->linkSelect('link');
        $form->datetimeRange('start_time', 'end_time', '有效期限:开始-结束')->required('不能为空');
        $form->imgUpload('pic_id', '封面');
        $form->number('sort', '权重')->help('排序时使用');
        $form->number('pos', '位置')->help('主题页住友分享和主题页好物推荐使用');
        $form->text('obj_id', '内容id')->help('主题页住友分享和主题页好物推荐使用,包含wiki');
        if(isset($request['AND'])){
            foreach($request['AND'] as $_k=>&$_v){
                if(!empty($_v)){
                    $_k = str_replace('[>=]','', $_k);
                    $_k = str_replace('[<]','', $_k);
                    $url_request[] =  $_k.'='.$_v;
                }
            }
            $url_request = implode('&', $url_request);
            $form->action($postUrl.'?'.$url_request);
        }else{
            $form->action($postUrl);
        }

        return $form->render();
    }



    public function advsList($request, $sid){
        //列表获取搜索条件
        $get = $_SERVER["QUERY_STRING"]?'?'.$_SERVER["QUERY_STRING"]:'';
        //按名称搜索时
        if(!empty($request['AND']['name'])){
            $sids = mSubject::getOneByWhere(['name'=>$request['AND']['name']],'id');
            if($sids){
                $request['OR'] = [
                    'sid'=> $sids,
                    'name'=> $request['AND']['name'],
                ];
                unset($request['AND']['name']);
                if(empty($request['AND'])){
                    unset($request['AND']);
                }
            }
        }
        if($sid > 0) {
            if (isset($request['AND'])) {
                $request['AND']['sid'] = $sid;
            } else {
                $request['sid'] = $sid;
            }
        }

        $adv = sMain::getAdv($request);
        $gridModel = new pGridDataModel(
            $adv['list'],
            $adv['total'],
            [
                'perPage' => self::PAGE_SIZE,
            ]
        );

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($get,$sid) {
            //$grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->between('date_time', '资源时间')->datetime()->condition($_GET);
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('show_type', '资源位置')->select(mAdv::SHOW_TYPE);
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('name', '名称')->placeholder('请输入名称');
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('group_title', '内容卡片标题')->placeholder();
                });
            });

            $grid->fixColumns(1,-2);

            $grid->column('id', 'id');
            $grid->column('rela_id', '关联分类');
            $grid->column('sid', '关联主题');
            $grid->column('show_type', '资源位置')->display(function(){
                return mAdv::SHOW_TYPE[$this->show_type];
            });
            $grid->column('name', '名称')->display(function(){
                if(!empty($this->name)) {
                    return '<p style="color:' . $this->font_color . ';">' . $this->name . '</p>';
                }else{
                    return '<p style="color:' . $this->font_color . ';">暂空</p>';
                }

            });
            $grid->column('group_title', '内容卡片');
            $grid->column('is_point', '背景是否透明')->display(function(){
                if($this->is_point) {
                    return '是';
                }else{
                    return '否';
                }
            });
            $grid->column('pic_id_url', '封面')->display(function(){
                if(!empty($this->pic_id_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >';
                }
            });
            $grid->column('sort', '权重');
            //$grid->column('link', '链接')->limit(30);
            $grid->column('link', '链接信息')->linkSelect();

            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '更新时间');
            $grid->column('status', '状态')->display(function(){
                switch ($this->status){
                    case 0:$st = '未生效';break;
                    case 1:$st = '开启';break;
                    case 2:$st = '已失效';break;break;
                }
                return $st;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions)use($get, $sid){
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();

                if($actions->row->status < 2) {
                    $actions->append("<a href=\"/admin/decoration/adv/".$sid."/create?id=" . $actions->row->id . "\" class=\"btn btn-primary\">编辑</a>");
                    $actions->append("<a href=\"/admin/decoration/adv/del/" . $actions->row->id . '/' . $sid . $get . "\" class=\"btn btn-primary\" onclick=\"return confirm('确认删除！！！'); \">删除</a>");
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    //单独创建分类首页banner广告位
    public function createAdv(){
        $adv = mCategory::getOneByWhere(['title'=>'推荐'],'id');

        return redirect('/admin/decoration/category/'.$adv.'/edit/adv/create');
    }


    //获取广告位
    public function _getShowtype($request, $showType = 0){
        $start_time =  date("Y-m-d H:i:s" ,time());
        $end_time = date("Y-m-d H:i:s" ,time());
        if($showType>0) {
            $request['AND']['show_type'] = $showType;
        }
        if(empty($request['AND'])){
            unset($request['AND']);
        }
        $request['AND']['start_time[<=]'] = $start_time;
        $request['AND']['end_time[>]'] = $end_time;


        $request['ORDER'] = ['pos' => 'ASC'];
        $count = mAdv::getCount($request);
        $data = mAdv::getAllByWhere($request);
        if($data && is_array($data)){
//            foreach($data as &$val){
//                $val['link'] = [
//                    'link_type' =>$val['link_type'],
//                    'link_params' => $val['link_params']
//                ];
//            }

        }
        $gridModel = new pGridDataModel($data, $count, [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($showType ) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->tools(function (Grid\Tools $tool) {

                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/maincategory/banner/create" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });

            $grid->column('id')->sort();
            $grid->column('pic_id_url', '封面')->display(function(){
                if(!empty($this->pic_id_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >';
                }
            });
            $grid->column('pos', '轮播位置');
            $grid->column('link', '链接信息')->linkSelect()->width(4,2);
            $grid->column('start_time', '展示时间')->display(function() {
                return '开始时间：'.$this->start_time." ~ ".'结束时间：'.$this->end_time;
            });

            $grid->column('status', '状态')->display(function(){
                switch ($this->status){
                    case 0:$st = '未生效';break;
                    case 1:$st = '开启';break;
                    case 2:$st = '已失效';break;break;
                }
                return $st;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                  //  $actions->disableView();
                    $actions->disableDelete();
                    $actions->disableEdit();
                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/maincategory/banner/create/'.$actions->row->id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	delcontent" data-id="' . $actions->row->id . '" href="javascript:void(0);">取消关联</a>');
            });

        });
        $list = $listGrid->render();
        return $list;
    }


    //public subject_list
    public  function ContentList(Request $request , Content $content , $sid)
    {
        $map =[
            'AND'  =>[
                'sid' => $sid,
                'status' => mAdv::STATUS_OPEN,
                'show_type' => mAdv::SHOW_TYPE_5,
            ],
            'ORDER' =>[
                'sort' => 'DESC',
                'edit_time'=> 'DESC'
            ]];

        $params  = $request->all();
        if($params['group_title']){
            $group_title = $params['group_title'] == "空" ? '': $params['group_title'];
            $map['AND']['group_title'] = $group_title;
        }
        $map = self::judgeIsOpen($params , $map);
        $subject_info =  mSubject::getOneByWhere(['id'=>$sid]);
        $info =  mAdv::getAllByWhere($map);
        if($info && is_array($info)){
           foreach($info as &$val){
                $val['group_title'] = $val['group_title'] ? : "空" ;
                if($val['obj_id'] == ''){
                    $params = json_decode($val['link_params'] , true);
                    $obj_id  = array_shift($params);
                    $val['obj_id'] = $obj_id;

                }
           }
       }

       $group_title = array_combine(array_unique(array_column($info,'group_title')) , array_unique(array_column($info,'group_title')));


        $gridModel = new pGridDataModel($info, count($info), [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use($group_title,$request,$sid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->filter(function (Grid\Filter $filter) use($group_title){
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) use($group_title) {
                    $filter->equal('group_title', '模块名称')->select($group_title);
                    $filter->equal('adv_status', '状态')->select(self::ADV_STATUS)->default(mAdv::STATUS_OPEN);
                });
            });
            $grid->tools(function (Grid\Tools $tool)use($request,$sid) {
//                $tool->append(new UserButton(UserButton::TYPE_HREF, '', '模块排序', '',
//                    '/admin/decoration/mainadv/moudlesort/'.$sid));
                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/mainadv/content/create/'.$sid.'" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });

            $grid->fixColumns(0, -1);
            $grid->column('id')->sort("contentEditTime");
            $grid->column('group_title', '组合内容')->display(function (){
                $display = [];
                $title = $this->group_title ? : "空";
                $display[] ="<sapn style='font-size: 15px;'>名称:<b>".$title."</b></sapn>" ;
                $display[] ="<sapn style='font-size: 15px'>权重:<b>" .$this->sort."</b></sapn>";
                return implode('<br/>', $display);

            });
            $grid->column('name', '封面标题')->display(function(){
                $html = '';
                if(!empty($this->pic_id_url)) {
                    $html= ' <h6>封面:</h6><img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >.<br/><br/>';
                }
                if(!empty($this->name)){
                    $html .="<h6>标题:</h6><b>".$this->name."</b>";
                }
                return $html;
            });

            $grid->column('link_type', '内容')->display(function(){
                $html = '';
                $html .="<span>类型:<b>".self::LINK_TYPE[$this->link_type]."</b></span><br/>";
                $html .="<span>obj_id:<b>".$this->obj_id."</b></span><br/>";
                return $html;
            });


//            $grid->column('sort', '权重');
       //     $grid->column('link', '链接信息')->linkSelect();
//            $grid->column('url', '链接信息')->display(function (){
//                return "<span>".$this->url."</span>";
//            });
            $grid->column('edit_time', '更新时间');

            $grid->column('start_time', '展示时间')->display(function() {
                return '开始时间：'.$this->start_time." ~ ".'结束时间：'.$this->end_time;
            });

            $grid->header(function () use ($sid) {
                $html = '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;注意：模块内按「更新时间」倒序排序 ,可通过「刷新时间」置顶内容</span>';
                return $html;
            });
            $grid->actions(function (Grid\Displayers\Actions $actions)use ($sid) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/mainadv/content/create/'.$sid.'/'.$actions->row->id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	deladv" data-id="' . $actions->row->id . '" data-sid="' . $sid . '" href="javascript:void(0);">删除</a>');

                    $actions->append('&nbsp;&nbsp;<a class="glyphicon glyphicon-refresh	reset-edittime" data-id="' . $actions->row->id . '" href="javascript:void(0);">刷新时间</a>');

            });
        });

        $list = $listGrid->render();
//        $tab = new Tab();
//        $tab->addlink($subject_info['name']."-热搜词" , "/admin/decoration/mainadv/taglist/".$sid);
//        $tab->add($subject_info['name']."-组合内容卡片" ,
//        $list ,true);
//        $tab->addLink($subject_info['name']."-轮播banner" ,"/admin/decoration/mainadv/subjectbannerlist/".$sid);

        return $content
            ->header('装修-[干货]节点模块-首屏文章')
            ->breadcrumb(
                ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
                ['text' => $subject_info['name'].'-组合内容卡片', 'url' => '/decoration/mainadv/moudlesort/'.$sid],
                ['text' => $subject_info['name'].'-内容卡片', 'url' => '/decoration/mainadv/subjectlist/'.$sid]
            )
            ->body($list);
    }




    public function contentEditTime(Request $request)
    {
        $params = $request->all();
        if($params['sort'] && is_array($params['sort'])){
            $result = mAdv::action(function()use($params){
                $edit_time = time();
                foreach($params['sort'] as $_k=>$pos){
                    $time = date("Y-m-d H:i:s",$edit_time - $pos);
                    if(!mAdv::updateData(['edit_time' => $time], ['id' => $_k])){
                        return false;
                    }
                }
                return true;
            });
        }
        if($result){
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }







    public function EditTime(Request $request, $id = 0)
    {
        try {
            if (!$id) {
                throw new \Exception('不存在的id');
            }
            mAdv::updateData(['edit_time' => date("Y-m-d H:i:s",time()) ,'admin_id' =>  Admin::user()->id],['id' => $id]);
            $success = [
                'title' => '任务 ID: ' . $id . ' 更新成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '更新失败',
                'code' => 0,
                'status' => false,
                'msg' => '错误信息#file:' . $e->getFile() . '#line:' . $e->getLine() . '#msg:' . $e->getMessage(),
            ];
        }
        return response()->json($success);
    }


    public function MoudleSort(Request $request ,Content $content, $sid)
    {
        $time = date("Y-m-d H:i:s", time());
        $map =[
            'AND'  =>[
                'sid' => $sid,
                'status' => mAdv::STATUS_OPEN,
                'show_type' => mAdv::SHOW_TYPE_5,
                'start_time[<=]' => $time,
                'end_time[>]' => $time,
            ],
            'ORDER' =>[
                'sort' => 'DESC',
                'edit_time'=> 'DESC'
            ]];


        $subject_info = mSubject::getOneByWhere(['id'=>$sid]);
        $moudle_info = SubjectGroup::getAllByWhere(['sid' => $sid , 'group_status'=>SubjectGroup::STATUS_OPEN, 'ORDER'=>['sort' => 'DESC']]);
        $moudle_group_info = [];
        if($moudle_info && is_array($moudle_info)){
             foreach($moudle_info as $moudle)
             {
                 $moudle['group_title'] =  $moudle['group_title'] ? : "空";

                     $moudle_group_info[$moudle['group_title']."-".$moudle['sort']]['title']  = $moudle['group_title'] ;
                 $moudle_group_info[$moudle['group_title']."-".$moudle['sort']]['id']  = $moudle['id'] ;
                 $moudle_group_info[$moudle['group_title']."-".$moudle['sort']]['sort']  = $moudle['sort'] ;
                     $moudle_group_info[$moudle['group_title']."-".$moudle['sort']]['moudle_id'] = $moudle['id'];


             }
        }
        $gridModel = new pGridDataModel($moudle_group_info, count($moudle_group_info), [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use($request,$sid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disablePagination();
            $grid->disableFilter();
            $grid->tools(function (Grid\Tools $tool)use($request,$sid) {
                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/mainadv/contentmoudle/create/'.$sid.'" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });
            $grid->column('id', 'id')->sort('sortmoudle');
            $grid->column('title', '模块名称');
            $grid->column('sort', '权重');
            $grid->actions(function (Grid\Displayers\Actions $actions) use($sid) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/mainadv/contentmoudle/create/'.$sid.'/'.$actions->row->moudle_id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	delmoudle" data-id="' . $actions->row->moudle_id . '" href="javascript:void(0);">删除</a>');
                $actions->append('<a href="/admin/decoration/mainadv/subjectlist/' . $sid.'?group_title='.$actions->row->title.'&sort='.$actions->row->sort.'" class="fa fa-info-circle">查看模块内容</a>');
            });
        });
        $list = $listGrid->render();
        $tab = new Tab();
        $tab->addlink($subject_info['name']."-热搜词" , "/admin/decoration/mainadv/taglist/".$sid);
        $tab->add($subject_info['name']."-组合内容卡片" ,
            $list ,true);
        $tab->addLink($subject_info['name']."-轮播banner" ,"/admin/decoration/mainadv/subjectbannerlist/".$sid);



        return $content
            ->header('模块排序')
            ->breadcrumb(
                ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
                ['text' => $subject_info['name'].'-组合内容页', 'url' => '/decoration/mainadv/moudlesort/'.$sid]
            )
            ->body($tab);
    }


    public  function conentdel(Request $request,$sid = 0 ,$id = 0)
    {
        $data = [
            'status'=>mAdv::STATUS_DELETE,
            'admin_id'=>Admin::user()->id,
            'edit_time'=>date("Y-m-d H:i:s" , time())
        ];
        $result = mAdv::updateData($data, ['id'=>$id, 'sid' =>$sid]);

        if($result){
            $success = [
                'title' =>  ' 更新成功',
                'code' => 1,
            ];


        }else{
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);

        }
        return response()->json($success);
    }


    public  function subjectdel(Request $request,$rela_id = 0 ,$id = 0)
    {
        $data = [
            'admin_id'=>Admin::user()->id,
            'edit_time'=>date("Y-m-d H:i:s" , time())
        ];
       $info =  mAdv::getOneByWhere(['id'=>$id]);
       $info['rela_id'] = trim($info['rela_id']);
       if(empty($info['rela_id']) || $info['rela_id'] == $rela_id){
           $data['status'] = mAdv::STATUS_DELETE;
       }elseif($info['rela_id']){
           $rela_ids = explode("," ,$info['rela_id']);
           $rela_ids = array_diff($rela_ids , [$rela_id]);
           $data['rela_id'] = implode(",",$rela_ids);
       }
        $result = mAdv::updateData($data, ['id'=>$id]);

        if($result){
            $success = [
                'title' =>  ' 更新成功',
                'code' => 1,
            ];


        }else{
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);

        }
        return response()->json($success);
    }



    private function resetEdittime()
    {
        return <<<SCRIPT
        $('.reset-edittime').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要刷新时间，id为 '+id+' 吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/decoration/mainadv/edittime/' +  id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        
        $('.deladv').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/decoration/mainadv/del/' + id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        
        
        $('.delmoudle').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/decoration/mainadv/delmoudle/' + id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            });
        })
        
        
        
        function closeLayer() {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        }
        $('.cancel-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要取消「'+group_time+'」的排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/cancelGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        $('.unlock-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要解除锁定的「'+group_time+'」排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/unlockGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        $('.lock-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要锁定「'+group_time+'」排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/lockGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        });
SCRIPT;
    }



    //taglist
    //public subject_list
    public  function taglist(Request $request , Content $content , $sid)
    {
        $map =[
            'AND'  =>[
                'sid' => $sid,
                'status' => mAdv::STATUS_OPEN,
                'show_type' => mAdv::SHOW_TYPE_6,
            ],
            'ORDER' =>[
                'sort' => 'DESC',
                'edit_time'=> 'DESC'
            ]];
        $params  = $request->all();

        //判断是否开启
        $map = self::judgeIsOpen($params , $map);
        $subject_info =  mSubject::getOneByWhere(['id'=>$sid]);
        $info =  mAdv::getAllByWhere($map);
        if($info && is_array($info)){
            foreach($info as &$val){
                $val['url'] = LinkFormat::generateLink($val['link_type'] , $val['link_params'])['app_template'];
            }
        }

        $tag_list = array_combine(array_column($info , 'name'),array_column($info,'is_point'));


        $gridModel = new pGridDataModel($info, count($info), [
            'perPage' => 100
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use($request,$sid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disablePagination();
            $grid->filter(function (Grid\Filter $filter){
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('adv_status', '状态')->select(self::ADV_STATUS)->default(mAdv::STATUS_OPEN);
                });

            });
            $grid->tools(function (Grid\Tools $tool)use($request,$sid) {
                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/mainadv/tag/create/'.$sid.'" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });

            $grid->fixColumns(0, -1);
            $grid->column('id')->sort();
            $grid->column('name', '热门名称');
            $grid->column('sort', '权重');
            $status = [
                'on' => [
                    'value' => 1,
                    'text' => '是'
                ],
                'off' => [
                    'value' => 0,
                    'text' => '否'
                ],
            ];
            $grid->column('is_point', '背景是否透明')->switchToggle($status);
//            $grid->column('url', '链接信息')->display(function (){
//                return "<span  style=''>".$this->url."</span>";
//            });
            $grid->column('link', '链接信息')->linkSelect();

            $grid->column('edit_time', '更新时间');

            $grid->column('start_time', '展示时间')->display(function() {
                return '开始时间：'.$this->start_time." ~ ".'结束时间：'.$this->end_time;
            });


            $grid->header(function () use ($sid) {
                $html = '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;注意：热搜词按按 「权重」排序';

                return $html;
            });
            $grid->actions(function (Grid\Displayers\Actions $actions)use ($sid) {
                $actions->disableEdit();
                $actions->disableDelete();

                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/mainadv/tag/create/'.$sid.'/'.$actions->row->id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	deladv" data-id="' . $actions->row->id . '" href="javascript:void(0);">删除</a>');
            });
        });

        $list = $listGrid->render();
        $tab = new Tab();
        $tab->add($subject_info['name'].'-热搜词' , $list);
        $tab->addLink($subject_info['name'].'-组合内容卡片' ,'/admin/decoration/mainadv/moudlesort/'.$sid);
        $tab->addLink($subject_info['name'].'-轮播banner' ,'/admin/decoration/mainadv/subjectbannerlist/'.$sid);


        return $content
            ->header('装修-[干货]节点模块-顶部标签')
            ->breadcrumb(
                ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
                ['text' => $subject_info['name'].'-热搜词', 'url' => '/decoration/mainadv/taglist/'.$sid]
            )
            ->body($tab);
    }

    //是否透明
    public function editTagIsShow(Request $request, $sid,$id){
        $params = $request->all();
        $params['id'] = $id;
        $param = [
            'is_show' => $params['is_show'] == 'on'? 1: 0,
            'admin_id' => Admin::user()->id,
            'edit_time' => date("Y-m-d H:i:s" , time())
        ];

        $result = mAdv::updateData($param,['id'=>$params['id'],'sid'=>$sid]);
        if($result){
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }


    //tag -- action

    public function createTag(Request $request ,Content $content,$sid = 0 , $id =0)
    {
        $info = [];
        if($id){
            $info = mAdv::getOneByWhere(['id'=>$id]);
            $info['link'] = [
                'link_type'=> $info['link_type'],
                'link_params'=> $info['link_params'],
            ];
        }
        $form =new Form($info);
        //获取所有分组
        $form->hidden('id');
        $form->text("name" , "名称")->required();
        $form->radio('is_point', '背景是否透明')
            ->options([0=>'否', 1=>'是'])->setWidth(4, 2);
        $form->linkSelect('link','跳转');

        $form->datetimeRange('start_time', 'end_time', '有效期限:开始-结束')->required('不能为空');
        $form->number("sort",'权重');
        $form->action('/admin/decoration/mainadv/tag/save/'.$sid);
        $list =  $form->render();
        $content->breadcrumb(
            ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
            ['text' => '-热搜词', 'url' => 'decoration/mainadv/taglist/'.$sid],
            ['text' => '新增', 'url' => '/decoration/mainadv/tag/create/'.$sid]);
        return $content->body($list);
    }



    public function tagSave(Request $request  , Content $content , $sid = 0  ,$id = 0)
    {
        $params = $request->all();
        $data = [];
        if($id){
            $text_id = $id;
            if(isset($params['is_point'])){
                $data['is_point'] = $params['is_point'] == "on" ? 1 : 0;
            }
            if($params['link_type'] && $params['link_params']){
                $data['link_type'] = $params['link_type'];
                $data['link_params'] = json_encode($params['link_params'] , true);
            }
        }else{
            $id = $params['id'] ? : 0;
            $data['sid'] = $sid;
            $data['show_type'] = mAdv::SHOW_TYPE_6;


            $data['name'] = $params['name']  ? : '';
            if($params['start_time'] && $params['end_time']){
                $data['start_time'] = $params['start_time'];
                $data['end_time'] = $params['end_time'];
            }
            $data['sort']  = $params['sort'] ? : 0;
            $data['is_point'] = $params['is_point'] ? : 0;
            $data['link_type'] = $params['link_type'];
            $data['link_params'] = json_encode($params['link_params'] , true);
        }
        if($id){
            $data['edit_time'] = date("Y-m-d H:i:s" ,time());
            $data['admin_id'] =  Admin::user()->id;
            $result =  mAdv::updateData($data,['id' => $id]);
        }else{
            $data['status'] = mAdv::STATUS_OPEN;
            $data['admin_id'] =  Admin::user()->id;
            $data['add_time'] = date("Y-m-d H:i:s" ,time());
            $result =  mAdv::addData($data);
        }
        if($result){
            if($text_id){
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);

            }else{
                $success = new MessageBag([
                    'title' => '操作成功'
                ]);

                return redirect('/admin/decoration/mainadv/taglist/'.$sid)->with(compact('success'));

            }

        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);

        }
    }

   //tag sort
    public function sort(Request $request){
        $params = $request->all();
        $params['sort'] = array_values(array_reverse(array_flip($params['sort'])));

        if($params['sort'] && is_array($params['sort'])){
            $result = mAdv::action(function()use($params){
                foreach($params['sort'] as $_k=>&$id){
                    if(!mAdv::updateData(['sort' => $_k], ['id' => $id])){
                        return false;
                    }
                }
                return true;
            });
        }
        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }


    public function delte(Request $request , Content $content , $id = 0)
    {

        $info = mAdv::getOneByWhere([
            'id' => $id
        ]);
        $data = [
            'admin_id'=>Admin::user()->id,
            'edit_time'=>date("Y-m-d H:i:s" , time()),
            'status' => mAdv::STATUS_DELETE
        ];


        $result = mAdv::updateData($data, ['id'=>$id]);

        if($result){
            $success = [
                'title' =>  ' 更新成功',
                'code' => 1,
            ];
        }else{
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);

        }
        return response()->json($success);
    }


    //content --action
    public function createContent(Request $request ,Content $content,$sid = 0 , $id=0)
    {
        $info = [];
        if($id){
            $info = mAdv::getOneByWhere(['id'=>$id]);
            $info['link'] = [
                'link_type'=> $info['link_type'],
                'link_params'=> $info['link_params'],
            ];
        }

        $subject_info = mSubject::getOneByWhere(['id' =>$sid]);
        //获取卡片名称
        $time = date("Y-m-d H:i:s", time());

        $groupTitleWhere = [
            'group_status[!]' => SubjectGroup::STATUS_DELETE
        ];
        if($sid > 0) {
            $groupTitleWhere['sid'] = $sid;
        }
        $groupTitle_arr = [];


        $groupTitle = SubjectGroup::getAllByWhere($groupTitleWhere );
        if($groupTitle && is_array($groupTitle)){
            foreach($groupTitle as $group){
                $groupTitle_arr[$group['id']] = $group['group_title'] ? : "空";
            }
        }
        if($info && is_array($info)){
            $group_info = SubjectGroup::getOneByWhere(['sid' =>$sid , 'group_status' => SubjectGroup::STATUS_OPEN , 'group_title' => $info['group_title'] , 'sort' => $info['sort']]);
            $info['group_title'] = $group_info['id'];
        }

        $form =new Form($info);
        //获取所有分组
        $form->hidden('id');

        $form->select('group_title', '组合名称')->options($groupTitle_arr)->required();
        $form->select('link_type', '内容类型')
            ->options(self::LINK_TYPE)->required();
        $form->text('obj_id', '内容id')->required();
        $form->text("name" , "标题")->help("输入标题可以 重命名 内容标题");
        $form->imgUpload('pic_id', '封面')->help("跳转链接只可以选择 '灵感集' '指南' '经验文章' '整屋案例' '专题' '话题详情页'");

        $form->datetimeRange('start_time', 'end_time', '有效期限:开始-结束')->required('不能为空');
       // $form->text("obj_id",'内容id')->required();
        $form->action('/admin/decoration/mainadv/content/save/'.$sid);
        $list =  $form->render();
        $content->breadcrumb(
            ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
            ['text' => $subject_info['name'].'-组合内容卡片', 'url' => 'decoration/mainadv/moudlesort/'.$sid],
            ['text' => '新增', 'url' => '/decoration/mainadv/content/create/'.$sid]);
        return $content->body($list);
    }



    public function contentSave(Request $request  , Content $content , $sid = 0 )
    {
        $params = $request->all();
        $data = [];
        $id = $params['id'] ? : 0;
        $data['sid'] = $sid;
        $data['show_type'] = mAdv::SHOW_TYPE_5;

        $data['link_type'] = $params['link_type'];
        $data['link_params'] = json_encode([self::TYPE_TO_OBJ_TYPE[$data['link_type']]=>$params['obj_id']] , true);
        $type_objId =   BlockTypeMapping::getObjFromLinkParams($params['link_type'] , $data['link_params']);
        $obj_id = $type_objId['obj_id'];
        $data['obj_id'] = $obj_id? : '';
        $data['name'] = $params['name']  ? : '';
        if($params['start_time'] && $params['end_time']){
            $data['start_time'] = $params['start_time'];
            $data['end_time'] = $params['end_time'];
        }
        if(isset($params['group_title'])) {
            $data['group_title'] = '';

            $info = SubjectGroup::getOneByWhere(['id' => $params['group_title'], 'group_status' => SubjectGroup::STATUS_OPEN, 'sid' => $sid]);
            $data['sort'] = $info['sort'];
            $data['group_title'] = $info['group_title'];
        }
        $data['pic_id'] = $params['pic_id'] ? : '';
        if($id){
          //  $data['edit_time'] = date("Y-m-d H:i:s" ,time());
            $data['admin_id'] = Admin::user()->id;

            $result =  mAdv::updateData($data,['id' => $id]);
        }else{
            $data['status'] = mAdv::STATUS_OPEN;
            $data['admin_id'] =  Admin::user()->id;
            $data['add_time'] = date("Y-m-d H:i:s" ,time());
            $result =  mAdv::addData($data);
        }
        if($result){
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/decoration/mainadv/subjectlist/'.$sid.'?group_title='.$data['group_title'])->with(compact('success'));
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }


    public function contentdel(Request $request , Content $content , $id = 0)
    {
        $data = [
            'admin_id'=>Admin::user()->id,
            'edit_time'=>date("Y-m-d H:i:s" , time()),
            'status' => mAdv::STATUS_DELETE
        ];
        $info =  mAdv::getOneByWhere(['id' =>$id]);
        $result = mAdv::updateData($data, ['id'=>$id]);
        if($result){
            $success = [
                'title' =>  ' 更新成功',
                'code' => 1,
            ];
        }else{
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }
        return response()->json($success);
    }

    //subjectbanner -- action
    public function createSubjectBanner(Request $request ,Content $content,$sid = 0 , $id=0)
    {
        $info = [];
        if($id){
            $info = mAdv::getOneByWhere(['id'=>$id]);
            $info['link'] = [
                'link_type'=> $info['link_type'],
                'link_params'=> $info['link_params'],
            ];
        }
        $subject_info = mSubject::getOneByWhere(['id' =>$sid]);

        $form =new Form($info);
        //获取所有分组
        $form->hidden('id');

        $form->imgUpload('pic_id', '封面')->help("跳转链接只可以选择");
        $form->linkSelect('link','跳转');
        $form->datetimeRange('start_time', 'end_time', '有效期限:开始-结束')->required('不能为空');
        $form->number('pos','位置')->required();

        $form->action('/admin/decoration/mainadv/subjectbanner/save/'.$sid);
        $list =  $form->render();
        $content->breadcrumb(
            ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
            ['text' => $subject_info['name'].'-轮播banner', 'url' => 'decoration/mainadv/subjectbannerlist/'.$sid],
            ['text' => '新增', 'url' => '/decoration/mainadv/content/create/'.$sid]);
        return $content->body($list);
    }



    public function SubjectBannerSave(Request $request  , Content $content , $sid = 0 ,$id=0)
    {
        $params = $request->all();
        $data = [];
        if($id){
            if($params['link_type'] && $params['link_params']){
                $data['link_type'] = $params['link_type'];
                $data['link_params'] = json_encode($params['link_params'] , true);
            }
        }else{
            $id = $params['id'] ? : 0;
            $data['sid'] = $sid;
            $data['show_type'] = mAdv::SHOW_TYPE_4;
            $data['link_type'] = $params['link_type'];
            $data['link_params'] = json_encode($params['link_params'] , true);
            $data['pic_id'] = $params['pic_id'] ? : '';
            $data['pos'] = $params['pos'] ? : 0;
            $data['start_time'] = $params['start_time'];
            $data['end_time'] = $params['end_time'];
        }

        if($id){
            $data['edit_time'] = date("Y-m-d H:i:s" ,time());
            $result =  mAdv::updateData($data,['id' => $id]);
        }else{
            $data['status'] = mAdv::STATUS_OPEN;
            $data['admin_id'] =  Admin::user()->id;
            $result =  mAdv::addData($data);
        }
        if($result){
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/decoration/mainadv/subjectbannerlist/'.$sid)->with(compact('success'));
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }



    public function createcontentMoudle(Request $request ,Content $content,$sid = 0 , $id=0)
    {
        $info = [];
        if($id){
            $info = SubjectGroup::getOneByWhere(['id'=>$id ,'sid'=>$sid]);
        }

        $subject_info = mSubject::getOneByWhere(['id' => $sid]);

        $form =new Form($info);
        //获取所有分组
        $form->hidden('id');
        $form->text('group_title' ,"组合名称")->help("如果不填 ，默认名称为 空");
        $form->number('sort','权重')->required();
        $form->action('/admin/decoration/mainadv/contentMoudleSave/save/'.$sid);
        $list =  $form->render();
        $content->breadcrumb(
            ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
            ['text' => $subject_info['name'].'-组合内容卡片', 'url' => 'decoration/mainadv/moudlesort/'.$sid],
            ['text' => '新增', 'url' => '/decoration/mainadv/content/create/'.$sid]);
        return $content->body($list);
    }



    public function contentMoudleSave(Request $request  , Content $content , $sid = 0 ,$id = 0)
    {
        $params = $request->all();
        $data = [];

        $id = $params['id'] ? : 0;
        $data['sid'] = $sid;
        $data['group_title'] = $params['group_title'] ? : '';
        $data['sort'] = $params['sort'] ? : 0;
        if($id){
            $data['admin_id'] =  Admin::user()->id;
            $data['edit_time'] = date("Y-m-d H:i:s" ,time());
            $this->updateContentGroup($id , $data);

            $result =  SubjectGroup::updateData($data,['id' => $id]);
        }else{
            $data['group_status'] = mAdv::STATUS_OPEN;
            $data['edit_time'] = date("Y-m-d H:i:s" ,time());
            $data['admin_id'] =  Admin::user()->id;
            $result =  SubjectGroup::addData($data);
        }
        if($result){
            $success = new MessageBag([
                'title' => '操作成功'
            ]);


            return redirect('/admin/decoration/mainadv/moudlesort/'.$sid)->with(compact('success'));
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }


    public function delContentGroup(Request $request  , Content $content , $id = 0)
    {

        $group_info = SubjectGroup::getOneByWhere(['id' => $id , 'status' => SubjectGroup::STATUS_OPEN]);

        $map=[
            'sid' => $group_info['sid'],
            'group_title' => $group_info['group_title'],
            'sort' => $group_info['sort'],
            'show_type' => mAdv::SHOW_TYPE_5
        ];
        $adv_info = mAdv::getAllByWhere($map);
        if($adv_info && is_array($adv_info) ){
            return response()->json([
                'code' => 0,
                'title' => "此模块还有 内容 ，请先删除 模块中内容",
            ]);
        }
        $data = [
            'group_status' =>  SubjectGroup::STATUS_DELETE,
            'admin_id' => Admin::user()->id,
            'edit_time' => date("Y-m-d H:i:s" ,time())
        ];
        $result = SubjectGroup::updateData($data,['id'=>$id]);
        if($result){
            $success = [
                'title' =>  ' 更新成功',
                'code' => 1,
            ];
        }else{
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }
        return response()->json($success);


    }


    public function updateContentGroup($group_id , $params)
    {
        $info = SubjectGroup::getOneByWhere(['id' => $group_id , 'status' => SubjectGroup::STATUS_OPEN]);
        $map=[
            'sid' => $info['sid'],
            'group_title' => $info['group_title'],
            'sort' => $info['sort'],
            'show_type' => mAdv::SHOW_TYPE_5
        ];
        $data = [];
        if(isset($params['group_title'])){
            $data['group_title'] = $params['group_title'];
        }
        if(isset($params['sort'])){
             $data['sort'] = $params['sort'];
        }
        if(isset($params['del_status'])){
            $data['status'] = $params['del_status'];
            $data['admin_id'] = $params['admin_id'];
            $data['edit_time'] = $params['edit_time'];
        }
        mAdv::updateData($data,$map);
    }

    //public subject_list
    public  function SubjectBannerList(Request $request , Content $content , $sid)
    {
        self::updateGroupData();
        $time = date("Y-m-d", time());
        $map =[
            'AND'  =>[
                'sid' => $sid,
                'status' => mAdv::STATUS_OPEN,
                'show_type' => mAdv::SHOW_TYPE_4,

            ],
            'ORDER' =>[
                'pos' => 'ASC',
            ]];

        $params  = $request->all();
        if($params['date_time']['start'] && $params['date_time']['end']){
            $map['AND']['start_time[>=]'] = $params['date_time']['start'];
             $map['AND']['end_time[<]'] = $params['date_time']['end'];
        }else{
            $map['AND']['start_time[<=]'] = $time;
            $map['AND']['end_time[>]'] = $time;

        }
        $map  = self::judgeIsOpen($params , $map);
        $subject_info = mSubject::getOneByWhere(['id' => $sid]);
        $info =  mAdv::getAllByWhere($map);



        $gridModel = new pGridDataModel($info, count($info), [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use($request,$sid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->filter(function (Grid\Filter $filter){
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('adv_status', '状态')->select(self::ADV_STATUS)->default(mAdv::STATUS_OPEN);
                    //$filter->between('date_time', '展示时间')->date()->condition($_GET)->default(mAdv::STATUS_OPEN);
                });

            });


            $grid->tools(function (Grid\Tools $tool)use($request,$sid) {

                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/mainadv/subjectbanner/create/'.$sid.'" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });

            $grid->fixColumns(0, -1);
            $grid->column('id')->sort("bannersort");
            $grid->column('pic_id_url', '内容展示')->display(function(){
                $html = '';

                    $html= ' <h6>封面:</h6><img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >.<br/><br/>';

                return $html;
            });
            $grid->column('pos', '位置');
            $grid->column('link', '链接信息')->linkSelect();
//            $grid->column('url', '链接信息')->display(function (){
//                return "<span>".$this->url."</span>";
//            });

            $grid->column('start_time', '展示时间')->display(function() {
                return '开始时间：'.$this->start_time." ~ ".'结束时间：'.$this->end_time;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions)use ($sid) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/mainadv/subjectbanner/create/'.$sid.'/'.$actions->row->id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	deladv" data-id="' . $actions->row->id . '" data-sid="' . $sid . '" href="javascript:void(0);">删除</a>');


            });
        });

        $list = $listGrid->render();
        $tab = new Tab();
        $tab->addlink($subject_info['name']."-热搜词" , "/admin/decoration/mainadv/taglist/".$sid);
        $tab->addLink($subject_info['name']."-组合内容卡片" ,
            "/admin/decoration/mainadv/moudlesort/".$sid);
        $tab->add($subject_info['name']."-轮播banner" ,$list,true);

        return $content
            //  ->header($subject_info['name'].'-主题内容页')
            ->breadcrumb(
                ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
                ['text' => $subject_info['name'].'-组合内容卡片', 'url' => '/decoration/mainadv/subjectlist/'.$sid]
            )
            ->body($tab);
    }


    //banner sort
    public function BannerSort(Request $request){
        $params = $request->all();
        if($params['sort'] && is_array($params['sort'])){
            $result = mAdv::action(function()use($params){
                foreach($params['sort'] as $_k=>$pos){
                    if(!mAdv::updateData(['pos' => $pos], ['id' => $_k])){
                        return false;
                    }
                }
                return true;
            });
        }
        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }


    //判断开始
    public function  judgeIsOpen($params , $map){
        $adv_status = !is_null($params['adv_status']) ?$params['adv_status'] : mAdv::STATUS_OPEN;
        $time = date("Y-m-d H:i:s", time());
        switch ($adv_status){
            case mAdv::STATUS_NOPEN:
                $map['start_time[>=]'] = $time;
                 break;
            case mAdv::STATUS_OPEN:
               $map['start_time[<=]'] = $time;
                $map['end_time[>]'] = $time;
                break;
            case mAdv::STATUS_CLOSE:
                $map['end_time[<]'] = $time;
                break;
        }
        return $map;
    }



    public function updateGroupData()
    {
        $subject_info = mSubject::getAllByWhere(['status'=>mSubject::STATUS_OPEN]);

        if($subject_info && is_array($subject_info)){
             foreach($subject_info as $subject){
                 $map =  [
                     'AND'  =>[
                         'sid' => $subject['id'],
                         'status' => mAdv::STATUS_OPEN,
                         'show_type' => mAdv::SHOW_TYPE_5,
                     ],
                     'ORDER' =>[
                         'sort' => 'DESC',
                         'edit_time'=> 'DESC'
                     ],
                     'GROUP' => 'sort'
                 ];
                  $adv_info = mAdv::getAllByWhere($map ,['sort','sid','group_title']);


                  if($adv_info && is_array($adv_info)){
                      foreach($adv_info as $group){
//                           SubjectGroup::addData([
//                               'sid' => $group['sid'],
//                               'group_title' => $group['group_title'],
//                               'sort' => $group['sort'],
//                               'admin_id' => Admin::user()->id,
//                               'edit_time'=>date("Y-m-d H:i:s" ,time()),
//                               'group_status' => SubjectGroup::STATUS_OPEN
//                           ]);
                      }
                  }

             }
        }
    }







}